﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using HISModels.Entities;
using HISModels.Enums;
using KeanuMvc.Reference;
using HISModels.ViewModel;

namespace HISRestServices.Services {

    [ServiceContract()]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class FrontOffice : BaseServices, IDisposable {

        #region Field
        private HttpStatusCode statusCode = new HttpStatusCode();
        private string detailMessage = string.Empty;
        #endregion

        #region Patient

        [WebGet(UriTemplate = "patient/{id}")]
        public HttpResponseMessage<VPatientData> GetPatientByID(int id) {

            HttpResponseMessage<VPatientData> returnValue = null;
            VPatientData data = null;
            try {


                data = new VPatientData();


                var pa = (from b in AppContext.Patients.Include("PatientPassIds").Include("SysFileUploads")
                          where b.Id == id && b.RecordStatus == 1
                          select b).First();

                var a = (from b in AppContext.Addresses
                         join c in AppContext.RefAreas on b.AreaId equals c.Id into q
                         from c in q.DefaultIfEmpty()
                         join d in AppContext.RefCities on b.CityId equals d.Id into r
                         from d in r.DefaultIfEmpty()
                         join e in AppContext.RefCountries on b.CountryId equals e.Id into s
                         from e in s.DefaultIfEmpty()
                         join f in AppContext.RefProvinces on b.ProvinceId equals f.Id into p
                         from f in p.DefaultIfEmpty()
                         where b.PatientId == id && b.RecordStatus == 1
                         select new ViewDataAddress {
                             AddressId = b.Id,
                             AddressDesc = b.AddressDesc,
                             AreaId = b.AreaId.Value == null ? 0 : b.AreaId.Value,
                             AreaName = c.AreaName == null ? string.Empty : c.AreaName,
                             CityId = b.CityId.Value == null ? 0 : b.CityId.Value,
                             CityName = d.NameValue == null ? string.Empty : d.NameValue,
                             CountryId = b.CountryId.Value == null ? 0 : b.CountryId.Value,
                             CountryName = e.NameValue == null ? string.Empty : e.NameValue,
                             ProvinceId = b.ProvinceId.Value == null ? 0 : b.ProvinceId.Value,
                             ProvinceName = f.NameValue == null ? string.Empty : f.NameValue,
                             PhoneNumber = b.PhoneNumber,
                             Fax = b.Fax,
                             ZipCode = b.ZipCode,
                             TypeId = b.TypeId
                         }).ToList();


                var pp = (from d in AppContext.PatientPayers
                          where d.PatientId == id
                          select d).ToList();

                var pr = (from f in AppContext.PatientRelatives.Include("Addresses")
                          where f.PatientId == id
                          select f).ToList();

                var h = (from g in AppContext.Banks.Include("Addresses").Include("RefPayerCategory") select g).ToList();

                var i = (from j in AppContext.Insurances.Include("Addresses").Include("RefPayerCategory") select j).ToList();

                data.Patient = pa;
                data.Patient.PatientPayers = pp;
                data.Patient.PatientRelatives = pr;
                data.ViewDataAddress = a;

                foreach (var patpayer in data.Patient.PatientPayers) {
                    if (patpayer.BankId != null) {
                        foreach (var listbank in h) {
                            if (patpayer.BankId == listbank.Id) {
                                patpayer.Bank = listbank;
                            }
                        }
                    }

                    if (patpayer.InsuranceId != null) {
                        foreach (var listinc in i) {
                            if (patpayer.InsuranceId == listinc.Id) {
                                patpayer.Insurance = listinc;
                            }
                        }
                    }
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<VPatientData>(statusCode);
                returnValue.Content = new ObjectContent<VPatientData>(data);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "patient/byname/")]
        public HttpResponseMessage<List<Patient>> GetPatientByName(string param) {
            string name = null;

            HttpResponseMessage<List<Patient>> returnValue = null;
            List<Patient> listpatient = null;
            try {
                name = param.Split('=')[1].NullSafeToString();

                var a = (from b in AppContext.Patients
                         where b.FirstName.Contains(name) || b.LastName.Contains(name) || b.MiddleName.Contains(name)
                               || (b.FirstName + " " + b.MiddleName + " " + b.LastName).Contains(name)
                         select b).Take(10).ToList();

                listpatient = a;

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<List<Patient>>(statusCode);
            returnValue.Content = new ObjectContent<List<Patient>>(listpatient);
            if (listpatient == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "patient/paging/")]
        public HttpResponseMessage<DataTablesNet> GetPatients(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] param = null;

            string mrn = string.Empty;
            string patientname = string.Empty;
            string dob = string.Empty;

            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                param = pagingSearch.sSearch.Split(';');

                mrn = param[0].Split('=')[1].NullSafeToString().Trim();
                patientname = param[1].Split('=')[1].NullSafeToString().Trim();
                dob = param[2].Split('=')[1].NullSafeToString().Trim();

                var a = from b in AppContext.Patients
                        join c in AppContext.Addresses on b.Id equals c.PatientId into d
                        from c in d.DefaultIfEmpty()
                        where b.RecordStatus == 1 && c.TypeId == 1
                        select new {
                            b.Id,
                            b.MedicalRecordNumber,
                            PatientName = (b.FirstName.Trim() + (b.MiddleName == null || b.MiddleName.Trim().Length == 0 ? " " : " " + b.MiddleName.Trim() + " ") + b.LastName.Trim()).Trim(),
                            b.FirstName,
                            b.MiddleName,
                            b.LastName,
                            b.Birthdate,
                            c.AddressDesc,
                            PhoneNumber = b.PhoneNumber
                        };
                //a = a.Distinct();
                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.MedicalRecordNumber.Contains(mrn) &&
                                (
                                     p.FirstName.Contains(patientname.Trim()) ||
                                     p.MiddleName.Contains(patientname.Trim()) ||
                                     p.LastName.Contains(patientname.Trim()) ||
                                     p.PatientName.Contains(patientname)

                                 )
                                 );

                if (dob != string.Empty) {
                    DateTime dd = DateTime.ParseExact(dob, HISModels.Enums.StaticVariables.DateFormat, null);
                    a = a.Where(p => p.Birthdate.Equals(dd));
                }
                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "patient/")]
        public HttpResponseMessage<Patient> UpdatePatient(Patient paramObject) {
            HttpResponseMessage<Patient> returnValue = null;
            string MrnNumb = string.Empty;

            try {

                foreach (var itempayer in paramObject.PatientPayers) {

                    if (itempayer.Id != 0) {
                        AppContext.PatientPayers.Attach(itempayer);
                        AppContext.Entry(itempayer).State = System.Data.EntityState.Modified;
                    } else {
                        AppContext.PatientPayers.Add(itempayer);
                    }
                }

                foreach (var fileupload in paramObject.SysFileUploads) {
                    if (fileupload.Id == 0) {
                        AppContext.SysFileUploads.Add(fileupload);
                    } else {
                        AppContext.Entry(fileupload).State = System.Data.EntityState.Modified;
                    }

                }

                foreach (var itempassport in paramObject.PatientPassIds) {
                    if (itempassport.Id == 0) {
                        AppContext.PatientPassIds.Add(itempassport);
                    } else {
                        AppContext.PatientPassIds.Attach(itempassport);
                        AppContext.Entry(itempassport).State = System.Data.EntityState.Modified;
                    }
                }

                foreach (var itemaddr in paramObject.Addresses) {
                    if (itemaddr.Id == 0) {
                        AppContext.Addresses.Add(itemaddr);
                    } else {
                        AppContext.Addresses.Attach(itemaddr);
                        AppContext.Entry(itemaddr).State = System.Data.EntityState.Modified;
                    }
                }

                foreach (var itempatrel in paramObject.PatientRelatives) {
                    if (itempatrel.Id != 0) {
                        AppContext.PatientRelatives.Attach(itempatrel);
                        AppContext.Entry(itempatrel).State = System.Data.EntityState.Modified;
                    } else {
                        AppContext.PatientRelatives.Add(itempatrel);
                    }

                    foreach (var addrrel in itempatrel.Addresses) {
                        if (addrrel.Id == 0) {
                            AppContext.Addresses.Add(addrrel);
                        } else {
                            AppContext.Addresses.Attach(addrrel);
                            AppContext.Entry(addrrel).State = System.Data.EntityState.Modified;
                        }
                    }
                }


                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Patient>(statusCode);
                returnValue.Content = new ObjectContent<Patient>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue; ;
        }

        [WebInvoke(Method = "POST", UriTemplate = "patient/")]
        public HttpResponseMessage<Patient> InsertPatient(Patient paramObject) {
            HttpResponseMessage<Patient> returnValue = null;

            string MrnNumb = string.Empty;
            RefHu hospital = Hospital;
            try {
                if (paramObject.MedicalRecordNumber == string.Empty) {
                    MrnNumb = NumberGenerator.Instance.GetMedicalRecordNumber(AppContext, Hospital.Id).MRNo;
                    paramObject.MedicalRecordNumber = MrnNumb;
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;

                    foreach (var fileupload in paramObject.SysFileUploads) {
                        AppContext.Entry(fileupload).State = System.Data.EntityState.Added;
                    }

                    foreach (var itempayer in paramObject.PatientPassIds) {
                        AppContext.Entry(itempayer).State = System.Data.EntityState.Added;
                    }

                    foreach (var itempatrel in paramObject.PatientRelatives) {
                        AppContext.Entry(itempatrel).State = System.Data.EntityState.Added;
                        foreach (var patreladdr in itempatrel.Addresses) {
                            AppContext.Entry(patreladdr).State = System.Data.EntityState.Added;
                        }
                    }
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Patient>(statusCode);
                returnValue.Content = new ObjectContent<Patient>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "patient/")]
        public HttpResponseMessage<string> DeletePatientByID(int id) {
            HttpResponseMessage<string> returnValue = null;
            try {
                Patient objectDelete = AppContext.Patients.Where(a => a.Id == id).First();
                objectDelete.RecordStatus = 0;
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<string>(statusCode);
            returnValue.Content = new ObjectContent<string>(detailMessage);
            if (detailMessage == string.Empty) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        #endregion

        #region Patient Payer
        [WebInvoke(Method = "POST", UriTemplate = "patient/payer/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAllPatientPayer(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] data = null;

            string x = string.Empty;
            int categoryid = 0;
            string payername = string.Empty;
            string payercode = string.Empty;
            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');

                x = data[0].Split('=')[1].NullSafeToString().Trim();
                if (x != "") {
                    categoryid = Convert.ToInt32(x);
                }

                payername = data[1].Split('=')[1].NullSafeToString().Trim();
                payercode = data[2].Split('=')[1].NullSafeToString().Trim();


                var a = (from b in AppContext.Banks
                         join c in AppContext.RefPayerCategories on b.CategoryId equals c.Id
                         join d in AppContext.Addresses on b.Id equals d.BankId into f
                         from d in f.DefaultIfEmpty()
                         select new PatientPayerData {
                             Id = b.Id,
                             CategoryId = b.CategoryId,
                             CategoryName = c.NameValue,
                             AddressDesc = d.AddressDesc,
                             Fax = d.Fax,
                             Phone = d.PhoneNumber,
                             PayerName = b.NameValue,
                             PayerCode = b.SwiftCode
                         }).Union(
                            from b in AppContext.Insurances
                            join c in AppContext.RefPayerCategories on b.CategoryId equals c.Id
                            join d in AppContext.Addresses on b.Id equals d.InsuranceId into f
                            from d in f.DefaultIfEmpty()
                            select new PatientPayerData {
                                Id = b.Id,
                                CategoryId = b.CategoryId,
                                CategoryName = c.NameValue,
                                AddressDesc = d.AddressDesc,
                                Fax = d.Fax,
                                Phone = d.PhoneNumber,
                                PayerName = b.NameValue,
                                PayerCode = b.CodeValue
                            }
                        );


                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.PayerName.Contains(payername) && p.PayerCode.Contains(payercode));

                if (categoryid != 0) {
                    a = a.Where(p => p.CategoryId == categoryid);
                }
                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }
        #endregion

        #region Registration
        [WebInvoke(Method = "POST", UriTemplate = "registration/")]
        public HttpResponseMessage<PatientReg> InsertRegistration(PatientReg paramObject) {
            HttpResponseMessage<PatientReg> returnValue = null;
            string MrnNumb = string.Empty;
            string Hucode = HospitalCode;
            RefHu hospital = Hospital;
            try {
                if (paramObject.Id == 0) {
                    paramObject.CodeValue = NumberGenerator.Instance.GetNewRegNumber(AppContext, paramObject.HuLobRelId).RegNumber;
                    paramObject.RecordStatus = 1;
                    paramObject.RegistrationTime = DateTime.Now;
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                }


                foreach (var docregrel in paramObject.DoctorRegRels) {
                    if (docregrel.Id == 0) {
                        AppContext.Entry(docregrel).State = System.Data.EntityState.Added;
                    } else {
                        AppContext.DoctorRegRels.Attach(docregrel);
                        AppContext.Entry(docregrel).State = System.Data.EntityState.Modified;
                    }
                }

                foreach (var docrefregrel in paramObject.DocRegRefRels) {
                    if (docrefregrel.Id == 0) {
                        AppContext.Entry(docrefregrel).State = System.Data.EntityState.Added;
                    } else {
                        AppContext.DocRegRefRels.Attach(docrefregrel);
                        AppContext.Entry(docrefregrel).State = System.Data.EntityState.Modified;
                    }
                }

                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<PatientReg>(statusCode);
                returnValue.Content = new ObjectContent<PatientReg>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
                returnValue.Headers.Add("HuCode", HospitalCode);
            }
            return returnValue;

        }

        [WebGet(UriTemplate = "registration/")]
        public HttpResponseMessage<string> CobaRegistration() {
            HttpResponseMessage<string> returnValue = null;
            string MrnNumb = string.Empty;
            string Hucode = HospitalCode;

            try {

                detailMessage = NumberGenerator.Instance.GetMedicalRecordNumber(AppContext, 1).MRNo;

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<string>(statusCode);
                returnValue.Content = new ObjectContent<string>(detailMessage);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;

        }

        [WebInvoke(Method = "POST", UriTemplate = "registration/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAllRegistrationToday(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] param = null;

            string regcode = string.Empty;
            string patientname = string.Empty;
            string doctorname = string.Empty;

            try {
                int huid = Hospital.Id;
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                param = pagingSearch.sSearch.Split(';');

                regcode = param[0].Split('=')[1].NullSafeToString().Trim();
                patientname = param[1].Split('=')[1].NullSafeToString().Trim();
                doctorname = param[2].Split('=')[1].NullSafeToString().Trim();

                var a = from b in AppContext.PatientRegs
                        join c in AppContext.DoctorRegRels on b.Id equals c.RegistrationId
                        join d in AppContext.Patients on b.PatientId equals d.Id
                        join e in AppContext.Doctors on c.DoctorId equals e.Id
                        join k in AppContext.Employees on e.EmployeeId equals k.Id
                        join g in AppContext.DoctorSpecRels on e.Id equals g.DoctorId
                        join h in AppContext.RefSubSpecialists on g.SubSpecialistId equals h.Id
                        join i in AppContext.RefSpecialists on h.SpecialistId equals i.Id
                        join j in AppContext.RefSpecialistGroups on i.GroupSpecialistId equals j.Id
                        join f in AppContext.HuLobRels on b.HuLobRelId equals f.Id
                        where b.RecordStatus == 1 && f.HospitalUnitId == huid && EntityFunctions.DiffDays(b.RegistrationTime, DateTime.Now) == 0
                        select new {
                            b.Id,
                            b.PatientId,
                            RegNumber = b.CodeValue,
                            d.FirstName,
                            d.MiddleName,
                            d.LastName,
                            PatientName = d.FirstName.Trim() + (d.MiddleName == null || d.MiddleName.Trim().Length == 0 ? " " : " " + d.MiddleName.Trim() + " ") + d.LastName.Trim(),
                            DoctorFirstName = k.FirstName,
                            DoctorLastName = k.LastName,
                            DoctorName = k.FirstName + " " + k.LastName,
                            GroupSpecialist = j.NameValue,
                            SubSpecialist = h.NameValue,
                            Specialist = i.NameValue,
                            FullSpecialist = j.NameValue + " " + h.NameValue + " " + i.NameValue
                        };

                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.RegNumber.Contains(regcode) &&
                                 (p.FirstName.Contains(patientname) ||
                                 p.MiddleName.Contains(patientname) ||
                                 p.LastName.Contains(patientname) ||
                                 p.PatientName.Contains(patientname)) &&
                                 (
                                 p.DoctorFirstName.Contains(doctorname) ||
                                 p.DoctorLastName.Contains(doctorname) ||
                                 p.DoctorName.Contains(doctorname)
                                 )
                                 );


                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }
        #endregion

        #region Appointment
        [WebGet(UriTemplate = "appointment/{id}")]
        public HttpResponseMessage<Appointment> GetAppointmentById(int id) {
            HttpResponseMessage<Appointment> returnValue = null;
            Appointment appointment = null;
            try {
                appointment = new Appointment();
                appointment = AppContext.Appointments.Include("DoctorSchedule").Where(a => a.Id == id).First();
                //--get doctor
                AppContext.DoctorSchedules.Include("Doctor").Where(a => a.DoctorId == appointment.DoctorSchedule.DoctorId).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Appointment>(statusCode);
                returnValue.Content = new ObjectContent<Appointment>(appointment);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "appointment/")]
        public HttpResponseMessage<Appointment> InsertAppointmentSchedule(string paramObject) {
            HttpResponseMessage<Appointment> returnValue = null;
            Appointment appointment = null;
            string[] arrParam = null;

            int docID = 0;
            bool isInRange = false;
            DateTime startDate = DateTime.Now;
            DateTime endDate = DateTime.Now;
            string title = string.Empty;
            string phone = string.Empty;
            int patientid = 0;
            try {
                arrParam = paramObject.Split(';');
                docID = Convert.ToInt32(arrParam[0].Split('=')[1]);
                startDate = DateTime.ParseExact(arrParam[1].Split('=')[1].NullSafeToString(), StaticVariables.DateTimeFormat, null);
                endDate = DateTime.ParseExact(arrParam[2].Split('=')[1].NullSafeToString(), StaticVariables.DateTimeFormat, null);
                title = arrParam[3].Split('=')[1].NullSafeToString();
                phone = arrParam[4].Split('=')[1].NullSafeToString();
                patientid = Convert.ToInt32(arrParam[5].Split('=')[1]);
                TimeSpan startTime = startDate.TimeOfDay;
                TimeSpan endTime = endDate.TimeOfDay;

                var a = AppContext.DoctorSchedules
                        .Where(d => d.DoctorId == docID &&
                                    d.DaySet == (int)startDate.DayOfWeek && d.RecordStatus == 1)
                        .First();
                TimeSpan temp = (TimeSpan)a.StartScheduleTime;
                var dataStartRange = new DateTime(startDate.Year, startDate.Month, startDate.Day, temp.Hours, temp.Minutes, 0);
                temp = (TimeSpan)a.EndScheduleTime;
                var dataEndRange = new DateTime(startDate.Year, startDate.Month, startDate.Day, temp.Hours, temp.Minutes, 0);

                isInRange = (dataStartRange <= startDate && dataEndRange >= startDate);

                appointment = new Appointment();
                appointment.DoctorScheduleId = a.Id;
                appointment.StartTime = startDate;
                appointment.EndTime = endDate;
                appointment.BookerName = title;
                appointment.IsInRange = isInRange ? 1 : 0;
                appointment.RecordStatus = 1;
                appointment.PhoneNumber = phone;
                appointment.PatientId = patientid;
                AppContext.Entry(appointment).State = System.Data.EntityState.Added;
                AppContext.SaveChanges(UserId);

                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<Appointment>(statusCode);
            returnValue.Content = new ObjectContent<Appointment>(appointment);
            returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "appointment/")]
        public HttpResponseMessage<Appointment> UpdateAppointmentSchedule(string paramObject) {
            HttpResponseMessage<Appointment> returnValue = null;
            Appointment appointment = null;
            string[] arrParam = null;

            int id = 0;
            string title = string.Empty;
            string phone = string.Empty;
            int patientid = 0;
            try {
                arrParam = paramObject.Split(';');
                id = Convert.ToInt32(arrParam[0].Split('=')[1]);
                title = arrParam[1].Split('=')[1].ToString();
                phone = arrParam[2].Split('=')[1].ToString();
                patientid = Convert.ToInt32(arrParam[3].Split('=')[1]);
                appointment = AppContext.Appointments.Where(d => d.Id == id && d.RecordStatus == 1).First();

                appointment.BookerName = title;
                appointment.PhoneNumber = phone;
                appointment.PatientId = patientid;
                AppContext.Entry(appointment).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<Appointment>(statusCode);
            returnValue.Content = new ObjectContent<Appointment>(appointment);
            returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "appointment/schedule/paging/")]
        public HttpResponseMessage<DataTablesNetAppointment> GetAppointmentSchedulePaging(PostDataTablesNet pagingSearch) {

            HttpResponseMessage<DataTablesNetAppointment> returnValue = null;
            List<DoctorScheduleData> listAppointment = null;
            DataTablesNetAppointment paging = null;
            string timeRange = string.Empty;
            string[] arrParam = null;

            int huId = 0;
            int specialistId = 0;
            string doctorName = string.Empty;
            int doctorId = 0;
            try {
                listAppointment = new List<DoctorScheduleData>();
                paging = new DataTablesNetAppointment();

                paging.sEcho = pagingSearch.sEcho;
                arrParam = pagingSearch.sSearch.Split(';');

                if (arrParam.Count() == 1) {
                    doctorId = Convert.ToInt32(arrParam[0].Split('=')[1]);

                } else {
                    huId = Convert.ToInt32(arrParam[0].Split('=')[1]);
                    specialistId = Convert.ToInt32(arrParam[1].Split('=')[1]);
                    doctorName = arrParam[2].Split('=')[1].NullSafeToString().Trim();
                }


                var a = from d in AppContext.Doctors
                        join i in AppContext.Employees on d.EmployeeId equals i.Id
                        join c in AppContext.DoctorHuRels on d.Id equals c.DoctorId
                        join e in AppContext.DoctorSpecRels on d.Id equals e.DoctorId
                        join f in AppContext.RefSubSpecialists on e.SubSpecialistId equals f.Id
                        join g in AppContext.RefSpecialists on f.SpecialistId equals g.Id
                        join h in AppContext.RefSpecialistGroups on g.GroupSpecialistId equals h.Id
                        where d.RecordStatus == 1
                        select new {
                            DoctorId = d.Id,
                            DoctorCode = d.CodeValue,
                            i.FirstName,
                            i.LastName,
                            c.HospitalUnitId,
                            DoctorName = i.FirstName + " " + i.LastName,
                            e.SubSpecialistId,
                            GroupSpecialist = h.NameValue,
                            SubSpecialist = f.NameValue,
                            Specialist = g.NameValue,
                        };



                paging.iTotalRecords = a.Count();
                if (doctorId != 0)
                    a = a.Where(p => p.DoctorId == doctorId);

                a = a.Where(d => d.FirstName.Contains(doctorName) || d.LastName.Contains(doctorName));

                if (huId != 0) {
                    a = a.Where(d => d.HospitalUnitId == huId);
                }
                if (specialistId != 0) {
                    a = a.Where(d => d.SubSpecialistId == specialistId);
                }
                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.DoctorId);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                var l = a.ToList();

                foreach (var item in l) {
                    DoctorScheduleData appdata = new DoctorScheduleData();
                    try {
                        var b = from c in AppContext.HuRooms
                                join d in AppContext.DoctorSchedules on c.Id equals d.HospitalUnitRoomId
                                join g in AppContext.HuWards on c.WardId equals g.Id
                                join f in AppContext.RefHus on g.HospitalUnitId equals f.Id
                                where d.RecordStatus == 1
                                select new { d.DoctorId, d.DaySet, HuName = f.NameValue, d.StartScheduleTime, d.EndScheduleTime };
                        b = b.Where(p => p.DoctorId == item.DoctorId);
                        var k = b.ToList();
                        foreach (var app in k) {

                            appdata.DoctorCode = item.DoctorCode;
                            appdata.Specialist = item.GroupSpecialist + " " + item.Specialist;
                            appdata.Location = app.HuName;
                            appdata.DoctorId = app.DoctorId.ToString();
                            appdata.DoctorName = item.DoctorName;
                            timeRange = new DateTime(app.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(app.EndScheduleTime.Value.Ticks).ToString("HH:mm") + "  ";
                            switch (app.DaySet) {
                                case 1: appdata.Monday += timeRange;
                                    break;
                                case 2:
                                    appdata.Tuesday += timeRange;
                                    break;
                                case 3:
                                    appdata.Wednesday += timeRange;
                                    break;
                                case 4:
                                    appdata.Thursday += timeRange;
                                    break;
                                case 5:
                                    appdata.Friday += timeRange;
                                    break;
                                case 6:
                                    appdata.Saturday += timeRange;
                                    break;
                                default:
                                    appdata.Sunday += timeRange;
                                    break;
                            }

                        }
                        if (k.Count > 0) {
                            listAppointment.Add(appdata);
                        }

                    } catch { }


                }

                paging.aaData = listAppointment;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNetAppointment>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNetAppointment>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "appointment/schedule/list/{id}")]
        public HttpResponseMessage<List<DoctorScheduleData>> GetAppointmentScheduleList(int id) {

            HttpResponseMessage<List<DoctorScheduleData>> returnValue = null;
            List<DoctorScheduleData> listDocShed = null;
            string timeRange = string.Empty;

            try {
                listDocShed = new List<DoctorScheduleData>();

                DoctorScheduleData docshedule = new DoctorScheduleData();

                var b = from c in AppContext.HuRooms
                        join d in AppContext.DoctorSchedules on c.Id equals d.HospitalUnitRoomId
                        join g in AppContext.HuWards on c.WardId equals g.Id
                        join f in AppContext.RefHus on g.HospitalUnitId equals f.Id
                        join a in AppContext.Doctors on d.DoctorId equals a.Id
                        join h in AppContext.DoctorSpecRels on a.Id equals h.DoctorId
                        join i in AppContext.RefSubSpecialists on h.SubSpecialistId equals i.Id
                        join j in AppContext.RefSpecialists on i.SpecialistId equals j.Id
                        join k in AppContext.RefSpecialistGroups on j.GroupSpecialistId equals k.Id
                        join m in AppContext.Employees on a.EmployeeId equals m.Id
                        where d.RecordStatus == 1 && d.DoctorId == id
                        select new { 
                            d.DoctorId, 
                            DoctorCode = a.CodeValue,
                            DoctorName = m.FirstName + " " +m.LastName,
                            d.DaySet, 
                            HuName = f.NameValue, 
                            d.StartScheduleTime, 
                            d.EndScheduleTime, 
                            GroupSpecialist = k.NameValue, 
                            Specialist = j.NameValue 
                        };
                var l = b.ToList();
                
                foreach (var dsch in l) {

                    docshedule.DoctorCode = dsch.DoctorCode;
                    docshedule.Specialist = dsch.GroupSpecialist + " " + dsch.Specialist;
                    docshedule.Location = dsch.HuName;
                    docshedule.DoctorId = dsch.DoctorId.ToString();
                    docshedule.DoctorName = dsch.DoctorName;
                    timeRange = new DateTime(dsch.StartScheduleTime.Value.Ticks).ToString("HH:mm") + "-" + new DateTime(dsch.EndScheduleTime.Value.Ticks).ToString("HH:mm") + "  ";
                    switch (dsch.DaySet) {
                        case 1: docshedule.Monday += timeRange;
                            break;
                        case 2:
                            docshedule.Tuesday += timeRange;
                            break;
                        case 3:
                            docshedule.Wednesday += timeRange;
                            break;
                        case 4:
                            docshedule.Thursday += timeRange;
                            break;
                        case 5:
                            docshedule.Friday += timeRange;
                            break;
                        case 6:
                            docshedule.Saturday += timeRange;
                            break;
                        default:
                            docshedule.Sunday += timeRange;
                            break;
                    }

                }
                if (l.Count > 0) {
                    listDocShed.Add(docshedule);
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<DoctorScheduleData>>(statusCode);
                returnValue.Content = new ObjectContent<List<DoctorScheduleData>>(listDocShed);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "appointment/registration/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAppointmentRegPaging(PostDataTablesNet pagingSearch) {

            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = new DataTablesNet();
            string[] data = null;

            int huId = Hospital.Id;
            int specialistId = 0;
            string doctorName = string.Empty;
            string bookername = string.Empty;

            try {

                paging.sEcho = pagingSearch.sEcho;
                data = pagingSearch.sSearch.Split(';');

                if (data.Count() > 0) {
                    bookername = data[0].Split('=')[1].NullSafeToString().Trim();
                    doctorName = data[1].Split('=')[1].NullSafeToString().Trim();
                    specialistId = Convert.ToInt32(data[2].Split('=')[1]);
                }


                var a = from d in AppContext.Doctors
                        join c in AppContext.DoctorHuRels on d.Id equals c.DoctorId
                        join e in AppContext.DoctorSpecRels on d.Id equals e.DoctorId
                        join f in AppContext.RefSubSpecialists on e.SubSpecialistId equals f.Id
                        join g in AppContext.RefSpecialists on f.SpecialistId equals g.Id
                        join h in AppContext.RefSpecialistGroups on g.GroupSpecialistId equals h.Id
                        join i in AppContext.DoctorSchedules on d.Id equals i.DoctorId
                        join j in AppContext.Appointments on i.Id equals j.DoctorScheduleId
                        join k in AppContext.Employees on d.EmployeeId equals k.Id
                        join o in AppContext.MemberEmployees on k.Id equals o.EmployeeId
                        join p in AppContext.SysMemberships on o.MembershipId equals p.Id
                        where d.RecordStatus == 1 && j.RecordStatus == 1 && i.RecordStatus == 1 && c.HospitalUnitId == huId && EntityFunctions.DiffDays(j.StartTime, DateTime.Now) == 0
                        select new {
                            AppointmentId = j.Id,
                            j.StartTime,
                            j.EndTime,
                            DoctorId = d.Id,
                            DoctorCode = d.CodeValue,
                            k.FirstName,
                            k.LastName,
                            c.HospitalUnitId,
                            DoctorName = (k.FirstName.Trim() + " " + k.LastName.Trim()).Trim(),
                            e.SubSpecialistId,
                            GroupSpecialist = h.NameValue,
                            SubSpecialist = f.NameValue,
                            Specialist = g.NameValue,
                            SpecialistId = g.Id,
                            j.BookerName,
                            j.Address,
                            j.PhoneNumber,
                            p.UserId
                        };



                paging.iTotalRecords = a.Count();

                a = a.Where(d => (d.FirstName.Contains(doctorName) || d.LastName.Contains(doctorName) || d.DoctorName.Contains(doctorName) || d.DoctorName.Contains(doctorName)) &&
                                  d.BookerName.Contains(bookername)
                                 );


                if (specialistId != 0) {
                    a = a.Where(d => d.SpecialistId == specialistId);
                }

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.DoctorId);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);


                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "appointment/schedule/")]
        public HttpResponseMessage<List<DoctorSchedule>> GetAppointmentSchedule(string paramObject) {
            HttpResponseMessage<List<DoctorSchedule>> returnValue;
            List<DoctorSchedule> doctorSched = null;

            string[] arrParam = null;
            int doctorId = 0;
            DateTime startDate = DateTime.Now.Date;
            DateTime endDate = DateTime.Now.Date.AddDays(30);

            try {

                arrParam = paramObject.Split(';');
                doctorId = Convert.ToInt32(arrParam[0].Split('=')[1]);
                startDate = DateTime.ParseExact(arrParam[1].Split('=')[1].NullSafeToString(), StaticVariables.DateFormat, null);
                endDate = DateTime.ParseExact(arrParam[2].Split('=')[1].NullSafeToString(), StaticVariables.DateFormat, null);

                doctorSched = AppContext.DoctorSchedules.Where(d => d.DoctorId == doctorId && d.RecordStatus == 1).ToList();

                foreach (var item in doctorSched) {
                    var c = AppContext.Appointments.Where(d => d.StartTime > startDate && d.EndTime < endDate && d.DoctorScheduleId == item.Id && d.RecordStatus == 1);
                    item.Appointments = c.ToList();
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<DoctorSchedule>>(statusCode);
                returnValue.Content = new ObjectContent<List<DoctorSchedule>>(doctorSched);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "appointment/")]
        public HttpResponseMessage<Appointment> DeleteAppointmentSchedule(int id) {
            HttpResponseMessage<Appointment> returnValue = null;
            Appointment appointment = null;

            try {

                appointment = AppContext.Appointments.Where(d => d.Id == id && d.RecordStatus == 1).First();
                appointment.RecordStatus = 0;

                AppContext.Entry(appointment).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);

                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<Appointment>(statusCode);
            returnValue.Content = new ObjectContent<Appointment>(appointment);
            returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            return returnValue;
        }
        #endregion

        #region Address
        //[WebGet(UriTemplate = "address/{id}")]
        //public HttpResponseMessage<AnonymousHeaderDetail> GetFullAddress(int id) {

        //    HttpResponseMessage<AnonymousHeaderDetail> returnValue = null;
        //    AnonymousHeaderDetail data = null;
        //    try {
        //        data = new AnonymousHeaderDetail();
        //        var a = from b in AppContext.Addresses
        //                join c in AppContext.RefAreas on b.AreaId equals c.Id into q
        //                from c in q.DefaultIfEmpty()
        //                join d in AppContext.RefCities on b.CityId equals d.Id into r
        //                from d in r.DefaultIfEmpty()
        //                join e in AppContext.RefCountries on b.CountryId equals e.Id into s
        //                from e in s.DefaultIfEmpty()
        //                join f in AppContext.RefProvinces on b.ProvinceId equals f.Id into p
        //                from f in p.DefaultIfEmpty()
        //                select new {
        //                    AddressId = b.Id,
        //                    b.AddressDesc,
        //                    b.AreaId,
        //                    c.AreaName,
        //                    b.CityId,
        //                    CityName = d.NameValue,
        //                    b.CountryId,
        //                    CountryName = e.NameValue,
        //                    b.ProvinceId,
        //                    ProvinceName = f.NameValue,
        //                    PhoneNumber = b.PhoneNumber,
        //                    Fax = b.Fax,
        //                    b.ZipCode
        //                };
        //        a = a.Where(p => p.AddressId == id);
        //        a = a.OrderBy(p => p.AddressId);
        //        data.Detail = a;
        //        statusCode = HttpStatusCode.OK;
        //    } catch (Exception ex) {
        //        statusCode = HttpStatusCode.InternalServerError;
        //        detailMessage = ex.Message;
        //    } finally {
        //        returnValue = new HttpResponseMessage<AnonymousHeaderDetail>(statusCode);
        //        returnValue.Content = new ObjectContent<AnonymousHeaderDetail>(data);
        //        returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
        //    }

        //    return returnValue;
        //}

        [WebInvoke(Method = "POST", UriTemplate = "address/")]
        public HttpResponseMessage<Address> InsertAddress(Address paramObject) {
            HttpResponseMessage<Address> returnValue = null;
            try {
                if (AppContext.Addresses.Where(d => d.Id == paramObject.Id).Count() > 0) {
                    detailMessage = "Address is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Address>(statusCode);
                returnValue.Content = new ObjectContent<Address>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "address/")]
        public HttpResponseMessage<Address> UpdateAddress(Address paramObject) {
            HttpResponseMessage<Address> returnValue = null;
            try {
                if (AppContext.Addresses.Where(d => d.Id != paramObject.Id).Count() > 0) {
                    detailMessage = "Address is already exist in Database!";
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<Address>(statusCode);
                returnValue.Content = new ObjectContent<Address>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebGet(UriTemplate = "addressbyid/{id}")]
        public HttpResponseMessage<ViewDataAddress> GetAddress(int id) {
            HttpResponseMessage<ViewDataAddress> returnValue = null;
            ViewDataAddress data = null;
            try {
                data = new ViewDataAddress();
                var a = from b in AppContext.Addresses
                        join c in AppContext.RefAreas on b.AreaId equals c.Id into q
                        from c in q.DefaultIfEmpty()
                        join d in AppContext.RefCities on b.CityId equals d.Id into r
                        from d in r.DefaultIfEmpty()
                        join e in AppContext.RefCountries on b.CountryId equals e.Id into s
                        from e in s.DefaultIfEmpty()
                        join f in AppContext.RefProvinces on b.ProvinceId equals f.Id into p
                        from f in p.DefaultIfEmpty()
                        select new ViewDataAddress {
                            AddressId = b.Id,
                            AddressDesc = b.AddressDesc,
                            AreaId = b.AreaId.Value == null ? 0 : b.AreaId.Value,
                            AreaName = c.AreaName == null ? string.Empty : c.AreaName,
                            CityId = b.CityId.Value == null ? 0 : b.CityId.Value,
                            CityName = d.NameValue == null ? string.Empty : d.NameValue,
                            CountryId = b.CountryId.Value == null ? 0 : b.CountryId.Value,
                            CountryName = e.NameValue == null ? string.Empty : e.NameValue,
                            ProvinceId = b.ProvinceId.Value == null ? 0 : b.ProvinceId.Value,
                            ProvinceName = f.NameValue == null ? string.Empty : f.NameValue,
                            PhoneNumber = b.PhoneNumber,
                            Fax = b.Fax,
                            ZipCode = b.ZipCode
                        };
                a = a.Where(p => p.AddressId == id);
                a = a.OrderBy(p => p.AddressId);
                data = a.First();


                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<ViewDataAddress>(statusCode);
                returnValue.Content = new ObjectContent<ViewDataAddress>(data);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        #endregion

        void IDisposable.Dispose() {
            try {
                base.Dispose();
                GC.SuppressFinalize(this);
            } catch { }
        }
    }
}